package com.itheima.web.servlet;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

/**
 * @author huyoufu <https://github.com/huyoufu>
 * @TIME 2020-08-13 14:10
 * @description
 */
@WebServlet("/upload1")
public class UploadServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        DiskFileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload fileUpload = new ServletFileUpload(factory);

        try {
            List<FileItem> items = fileUpload.parseRequest(request);

            for (FileItem item : items) {
                if (item.isFormField()){
                    //普通项
                    String paramName = item.getFieldName();
                    String paramValue = item.getString("utf-8");
                    System.out.println("普通表单项:"+paramName+"---"+paramValue);

                }else{
                    String paramName = item.getFieldName();
                    System.out.println("文件项:"+paramName);

                    InputStream in = item.getInputStream();

                    System.out.println("文件流:"+in);

                    System.out.println("文件类型:"+item.getContentType());
                }

            }
        } catch (FileUploadException e) {
            e.printStackTrace();
        }


    }
}
